import { Init, Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsInfoEntity } from '../entity/info';
import { GoodsSpecService } from './spec';
import { LessThan, MoreThan } from 'typeorm';
/**
 * 文章信息
 */
@Provide()
export class GoodsInfoService extends BaseService {
  @InjectEntityModel(GoodsInfoEntity)
  goodsInfoEntity: Repository<GoodsInfoEntity>;

  @Inject()
  goodsSpecService: GoodsSpecService;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.goodsInfoEntity);
  }

  /**
   * 修改之后
   * @param data
   * @param type
   */
  async modifyAfter(data: any, type: 'add' | 'update' | 'delete') {
    if ((type == 'add' || type == 'update') && data.specs) {
      // 保存规格
      await this.goodsSpecService.save(data.id, data.specs);
    }
    if (type == 'delete') {
      // 删除规格
      await this.goodsSpecService.removeByGoodsId([data.id]);
    }
  }

  /**
   * 详情
   * @param id
   * @param infoIgnoreProperty
   * @returns
   */
  async info(id: any, infoIgnoreProperty?: string[]) {
    if (!id) return;
    const info = await super.info(id, infoIgnoreProperty);

    return info;
  }

  async prevNext(id) {
    const current = await this.service.info(id);
    const { tp, typeId, ztype } = current;
    const prev = await this.goodsInfoEntity.findOne({
      where: { id: LessThan(id), tp, typeId, ztype },
      order: { id: 'DESC' },
    });

    const next = await this.goodsInfoEntity.findOne({
      where: { id: MoreThan(id), tp, typeId, ztype },
      order: { id: 'ASC' },
    });
    return { prev, current, next };
  }

  async years() {
    const queryBuilder = this.goodsInfoEntity
      .createQueryBuilder('goods')
      .select('DISTINCT goods.year', 'year') // Select distinct years
      .where('goods.tp = :tp', { tp: 1 })
      .andWhere('goods.status=:status', { status: 1 })
      .orderBy('goods.year', 'DESC'); // Sort by year

    const result = await queryBuilder.getRawMany();
    const years = result.map(item => item.year);

    return years;
  }
}
